<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { listActivities, addActivity, updateActivity, removeActivity } from '../services/activityApi'
import { Edit, Delete } from '@element-plus/icons-vue'

// 搜索表单
const qChannel = ref('') // 线上活动/推广介绍
const qType = ref('')    // 课程折扣/代金券
const qStatus = ref('')  // 未开始/进行中/已结束

// 列表与分页
const list = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const lastAction = ref('init')

// 轻量提示（Toast）
const toast = reactive({ show: false, type: 'info', text: '' })
function notify(text, type='info'){ toast.text=text; toast.type=type; toast.show=true; setTimeout(()=>toast.show=false,2000) }

function statusCodeOf(a){ const now=new Date().getTime(); const s=new Date(a.startTime).getTime(); const e=new Date(a.endTime).getTime(); if(isNaN(s)||isNaN(e)) return undefined; if(now<s) return 1; if(now>e) return 3; return 2 }

async function loadList(){
  loading.value = true
  try{
    const { list: rows, total: t } = await listActivities({ page: page.value, pageSize: pageSize.value, channel: qChannel.value, type: qType.value, status: qStatus.value })
    let data = rows || []
    if(qStatus.value){ data = data.filter(a=>statusCodeOf(a)===Number(qStatus.value)) }
    list.value = data
    total.value = t || data.length || 0
    if(total.value===0 && lastAction.value!=='page') notify('暂无数据','info')
  }catch(e){ notify(e.message||'不好意思，请稍后重试','error') }
  finally{ loading.value=false }
}

function search(silent=false){ page.value=1; lastAction.value='search'; if(!silent) notify('已应用筛选条件','info'); loadList() }
function clear(){ qChannel.value=''; qType.value=''; qStatus.value=''; page.value=1; lastAction.value='clear'; notify('已重置筛选条件','info'); loadList() }

// 弹窗
const showAdd = ref(false)
const showEdit = ref(false)
const showDelete = ref(false)
const form = reactive({ id:null, channel:'', name:'', type:'', discount:'', voucher:'', description:'', startTime:'', endTime:'' })
const currentId = ref(null)

function openAdd(){ Object.assign(form,{ id:null, channel:'', name:'', type:'', discount:'', voucher:'', description:'', startTime:'', endTime:'' }); showAdd.value=true }
async function confirmAdd(){
  try{
    const payload = { channel: form.channel, name: form.name, startTime: form.startTime, endTime: form.endTime, description: form.description, type: form.type, discount: null, voucher: null }
    if(form.type==='课程折扣'){ payload.discount = Number(form.discount)||null; payload.voucher = null }
    else { payload.voucher = Number(form.voucher)||null; payload.discount = null }
    await addActivity(payload)
    showAdd.value=false; notify('添加成功','success'); lastAction.value='add'; loadList()
  }catch(e){ notify(e.message||'不好意思，请稍后重试','error') }
}

function openEdit(row){ Object.assign(form,row); currentId.value=row.id; showEdit.value=true }
async function confirmEdit(){
  try{
    const payload = { channel: form.channel, name: form.name, startTime: form.startTime, endTime: form.endTime, description: form.description, type: form.type, discount: null, voucher: null }
    if(form.type==='课程折扣'){ payload.discount = Number(form.discount)||null }
    else { payload.voucher = Number(form.voucher)||null }
    await updateActivity(currentId.value, payload)
    showEdit.value=false; notify('修改成功','success'); lastAction.value='edit'; loadList()
  }catch(e){ notify(e.message||'不好意思，请稍后重试','error') }
}

function openDelete(row){ currentId.value=row.id; Object.assign(form,row); showDelete.value=true }
async function confirmDelete(){
  try{ await removeActivity(currentId.value); showDelete.value=false; if(list.value.length===1 && page.value>1) page.value-=1; notify('删除成功','success'); lastAction.value='delete'; loadList() }
  catch(e){ notify(e.message||'不好意思，请稍后重试','error') }
}

const rowStartIndex = computed(()=> (page.value-1)*pageSize.value )

onMounted(loadList)
watch(page,(nv,ov)=>{ if(nv!==ov){ lastAction.value='page'; notify(`已跳转到第 ${nv} 页`,'info'); loadList() } })
watch(pageSize,(nv,ov)=>{ if(nv!==ov){ lastAction.value='pageSize'; page.value=1; notify(`每页显示 ${nv} 条`,'info'); loadList() } })
</script>

<template>
  <div class="container">
    <div class="toolbar">
      <div class="filter-row">
        <div class="field"><span class="label">渠道来源：</span>
          <select v-model="qChannel"><option value="">请选择</option><option value="线上活动">线上活动</option><option value="推广介绍">推广介绍</option></select>
        </div>
        <div class="field"><span class="label">活动类型：</span>
          <select v-model="qType"><option value="">请选择</option><option value="课程折扣">课程折扣</option><option value="代金券">代金券</option></select>
        </div>
        <div class="field"><span class="label">活动状态：</span>
          <select v-model.number="qStatus"><option value="">请选择</option><option :value="1">未开始</option><option :value="2">进行中</option><option :value="3">已结束</option></select>
        </div>
        <div class="actions"><button class="btn" @click="search"><span class="icon">🔍</span>搜索</button><button class="btn btn-secondary" @click="clear"><span class="icon">♻️</span>重置</button></div>
      </div>
      <div class="toolbar-divider"></div>
      <div class="action-row">
        <button class="btn btn-primary" @click="openAdd">+ 创建活动</button>
      </div>
    </div>

    <div class="table-card">
      <table>
        <tr>
          <th>序号</th><th>活动名称</th><th>渠道来源</th><th>活动类型</th><th>活动细则</th><th>开始时间</th><th>结束时间</th><th>操作</th>
        </tr>
        <tr v-if="loading"><td colspan="8" class="loading">正在加载...</td></tr>
        <tr v-for="(a,i) in list" :key="a.id">
          <td>{{ rowStartIndex + i + 1 }}</td>
          <td>{{ a.name }}</td>
          <td>{{ a.channel }}</td>
          <td>{{ a.type }}</td>
          <td class="intro">{{ a.type==='课程折扣' && a.discount? `课程打折/${a.discount}折` : a.type==='代金券' && a.voucher? `代金券金额/${a.voucher}元` : '' }}</td>
          <td>{{ a.startTime }}</td>
          <td>{{ a.endTime }}</td>
          <td><el-button size="small" type="primary" @click="openEdit(a)"><el-icon><Edit/></el-icon>修改</el-button>
          <el-button size="small" type="danger" @click="openDelete(a)"><el-icon><Delete/></el-icon>删除</el-button>
          </td>
        </tr>
        <tr v-if="!loading && list.length===0"><td colspan="8" class="empty">暂无数据</td></tr>
      </table>
    </div>

    <div class="pagination">
      <div class="left">共 {{ total }} 条记录 第 {{ page }} / {{ Math.max(1, Math.ceil(total / pageSize)) }} 页</div>
      <div class="pages">
        <button class="page" :disabled="page===1" @click="page=1">«</button>
        <button class="page" :disabled="page===1" @click="page--">‹</button>
        <button v-for="p in Math.min(Math.ceil(total / pageSize), 9)" :key="p" class="page" :class="{ active: page===p }" @click="page=p">{{ p }}</button>
        <button class="page" :disabled="page===Math.ceil(total/pageSize)" @click="page++">›</button>
        <button class="page" :disabled="page===Math.ceil(total/pageSize)" @click="page=Math.ceil(total/pageSize)">»</button>
      </div>
      <div class="right"><select v-model.number="pageSize" @change="page=1"><option :value="10">10条/页</option><option :value="20">20条/页</option><option :value="50">50条/页</option></select></div>
    </div>

    <!-- 添加活动 -->
    <div v-if="showAdd" class="modal">
      <div class="dialog">
        <div class="dialog-header">创建活动</div>
        <div class="dialog-body">
          <div class="form-grid">
            <label>渠道来源</label>
            <select v-model="form.channel"><option value="线上活动">线上活动</option><option value="推广介绍">推广介绍</option></select>
            <label>活动名称</label>
            <input v-model="form.name" placeholder="请输入活动名称" />
            <label>活动类型</label>
            <select v-model="form.type"><option value="课程折扣">课程折扣</option><option value="代金券">代金券</option></select>
            <template v-if="form.type==='课程折扣'">
              <label>课程折扣</label>
              <input v-model="form.discount" type="number" step="0.1" min="0" placeholder="如 9.0 表示九折" />
            </template>
            <template v-else>
              <label>代金券金额（元）</label>
              <input v-model="form.voucher" type="number" min="0" placeholder="请输入金额" />
            </template>
            <label>开始时间</label>
            <input v-model="form.startTime" type="datetime-local" />
            <label>结束时间</label>
            <input v-model="form.endTime" type="datetime-local" />
            <label>活动简介</label>
            <textarea v-model="form.description" rows="3" placeholder="请输入活动简介"></textarea>
          </div>
        </div>
        <div class="dialog-footer"><button class="btn btn-secondary" @click="showAdd=false">取消</button><button class="btn" @click="confirmAdd">确定</button></div>
      </div>
    </div>

    <!-- 编辑活动 -->
    <div v-if="showEdit" class="modal">
      <div class="dialog">
        <div class="dialog-header">修改活动</div>
        <div class="dialog-body">
          <div class="form-grid">
            <label>渠道来源</label>
            <select v-model="form.channel"><option value="线上活动">线上活动</option><option value="推广介绍">推广介绍</option></select>
            <label>活动名称</label>
            <input v-model="form.name" />
            <label>活动类型</label>
            <select v-model="form.type"><option value="课程折扣">课程折扣</option><option value="代金券">代金券</option></select>
            <template v-if="form.type==='课程折扣'">
              <label>课程折扣</label>
              <input v-model="form.discount" type="number" step="0.1" min="0" />
            </template>
            <template v-else>
              <label>代金券金额（元）</label>
              <input v-model="form.voucher" type="number" min="0" />
            </template>
            <label>开始时间</label>
            <input v-model="form.startTime" type="datetime-local" />
            <label>结束时间</label>
            <input v-model="form.endTime" type="datetime-local" />
            <label>活动简介</label>
            <textarea v-model="form.description" rows="3"></textarea>
          </div>
        </div>
        <div class="dialog-footer"><button class="btn btn-secondary" @click="showEdit=false">取消</button><button class="btn" @click="confirmEdit">保存</button></div>
      </div>
    </div>

    <!-- 删除确认 -->
    <div v-if="showDelete" class="modal">
      <div class="dialog small">
        <div class="dialog-header">确认删除</div>
        <div class="dialog-body">是否删除活动“{{ form.name }}”？此操作不可恢复。</div>
        <div class="dialog-footer"><button class="btn btn-secondary" @click="showDelete=false">取消</button><el-button type="danger" @click="confirmDelete"><el-icon><Delete/></el-icon>删除</el-button></div>
      </div>
    </div>

    <div v-if="toast.show" class="toast" :class="toast.type">{{ toast.text }}</div>
  </div>
</template>

<style scoped>
.container{ width:100%; padding:0 16px 16px; position:relative; }
.toolbar{ display:flex; flex-direction:column; gap:12px; }
.filter-row{ display:flex; align-items:center; gap:12px; flex-wrap:nowrap; }
.action-row{ display:flex; align-items:center; gap:10px; }
.toolbar-divider{ height:1px; background:#e5e7eb; }
.toolbar .spacer{ width:8px; }
.field{ display:flex; align-items:center; gap:8px; }
.label{ color:#374151; }
.actions{ margin-left:auto; display:flex; gap:10px; }
.table-card{ margin-top:14px; background:#fff; border:1px solid #e5e7eb; border-radius:12px; box-shadow:0 6px 16px rgba(0,0,0,0.06); overflow-x:auto; min-height:520px; }
.table-card table{ width:100%; border-collapse:collapse; }
.table-card th,.table-card td{ border:1px solid #e5e7eb; line-height:52px; text-align:center; }
.table-card th{ background:#f7f7f8; color:#374151; font-weight:600; }
.table-card .intro{ max-width:360px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.table-card .loading,.table-card .empty{ color:#6b7280; height:60px; }
.pagination{ display:flex; align-items:center; justify-content:space-between; gap:12px; margin-top:14px; }
.pagination .left{ color:#666; }
.pagination .pages{ display:flex; gap:6px; }
.page{ padding:4px 10px; border:1px solid #e5e7eb; border-radius:6px; background:#fff; cursor:pointer; }
.page.active{ background:#08dcf3; border-color:#08dcf3; color:#0f172a; }
.page:disabled{ opacity:.5; cursor:not-allowed; }
.pagination .right select{ padding:6px 8px; border:1px solid #d1d5db; border-radius:6px; }
input,select,textarea{ padding:8px 10px; border:1px solid #d1d5db; border-radius:6px; background:#fff; min-width:160px; }
.btn{ background:#08dcf3; color:#0f172a; padding:8px 20px; border-radius:8px; border:1px solid #08dcf3; cursor:pointer; }
.btn:hover{ opacity:.9; }
.btn-primary{ background:#1677ff; border-color:#1677ff; color:#fff; }
.btn-secondary{ background:#fff; border-color:#cbd5e1; color:#0f172a; }
.btn.danger{ background:#ff4d4f; border-color:#ff4d4f; color:#fff; }
.modal{ position:fixed; inset:0; background:rgba(0,0,0,.35); display:grid; place-items:center; z-index:1000; }
.dialog{ background:#fff; border-radius:12px; width:720px; max-width:calc(100% - 48px); box-shadow:0 10px 24px rgba(0,0,0,.15); }
.dialog.small{ width:420px; }
.dialog-header{ padding:14px 18px; font-weight:600; border-bottom:1px solid #eee; }
.dialog-body{ padding:16px 18px; color:#333; }
.dialog-footer{ padding:12px 18px; display:flex; justify-content:flex-end; gap:10px; border-top:1px solid #eee; }
.form-grid{ display:grid; grid-template-columns:120px 1fr; gap:12px; align-items:center; }
.form-grid textarea{ grid-column:1/-1; }
.link{ background:none; border:none; color:#1677ff; cursor:pointer; }
.link.danger{ color:#ff4d4f; }
.toast{ position:fixed; top:18px; left:50%; transform:translateX(-50%); padding:10px 14px; border-radius:8px; color:#0f172a; box-shadow:0 8px 20px rgba(0,0,0,.12); z-index:2000; background:#fff; border:1px solid #e5e7eb; }
.toast.success{ background:#e6fffb; border-color:#b5f5ec; }
.toast.error{ background:#fff1f0; border-color:#ffccc7; }
.toast.info{ background:#f0f9ff; border-color:#bae6fd; }
</style>
